package com.free.javadodo.jdbc;

import java.sql.*;
import java.util.*;

import javax.sql.rowset.CachedRowSet;

import com.free.javadodo.ds.ui.DataSourceModel;
import com.sun.rowset.CachedRowSetImpl;

public class QueryHelper {
	private ConnectionManager connmgr;

	public QueryHelper() {
		 
	}

	public QueryHelper(DataSourceModel model) {
		connmgr = new ConnectionManager(model);
	}

	public QueryHelper(String driver, String ds, String user, String pwd) {
		connmgr = new ConnectionManager(driver, ds, user, pwd);
	}

	public ResultSet executeQuery(String sql) throws SQLException {
		Exception exception;
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		ResultSetMetaData meta = null;
		try {
			conn = connmgr.getConnection();
			stmt = conn.createStatement();

			long exetime = System.currentTimeMillis();
			rs = stmt.executeQuery(sql);
			exetime = System.currentTimeMillis() - exetime;
			if (exetime > 2000L) {

			}

		} catch (SQLException ex) {

			throw ex;
		} finally {
			CloseConn(rs, stmt, conn);
		}
		CloseConn(rs, stmt, conn);
		return rs;
	}

	public ResultSet getCachedRowSet(String sql) throws Exception {
		Connection conn = null;
		CachedRowSet crs = null; 
		try {
			crs = new CachedRowSetImpl();
			/*Class.forName(connmgr.getDriverClassName());
			crs.setUrl(connmgr.getConurl());
			crs.setUsername(connmgr.getUser());
			crs.setPassword(connmgr.getPwd());*/
			conn = connmgr.getConnection();
			crs.setCommand(sql);
			crs.execute( conn );
		 
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		} finally {
			CloseConn( null,null,conn);
		}
		CloseConn( null,null,conn);
		return crs;
	}
	

	public ResultSet executeQuery(String sql,Connection conn) throws SQLException {
		Exception exception;
	 
		Statement stmt = null;
		ResultSet rs = null;
		ResultSetMetaData meta = null;
		try {
			conn = connmgr.getConnection();
			stmt = conn.createStatement();

			long exetime = System.currentTimeMillis();
			rs = stmt.executeQuery(sql);
			exetime = System.currentTimeMillis() - exetime;
			if (exetime > 2000L) {

			}

		} catch (SQLException ex) {

			throw ex;
		} finally {
			//CloseConn(rs, stmt, conn);
		}
		//CloseConn(rs, stmt, conn);
		return rs;
	}

	private void CloseConn(ResultSet rs, Statement stmt, Connection conn) {
		
//		try {
//			if (rs != null) {
//				rs.close();
//			}
//		} catch (Exception ex) {
//		}
//		 
//		try {
//			if (stmt != null) {
//				stmt.close();
//			}
//		} catch (Exception ex) {
//
//		}
//		System.out.println()
		try {
			if ( conn != null && conn.isClosed() == false ) {
				conn.close();
			}
		} catch (Exception ex) {

		}
	}

}
